package cn.swanit.service.demo.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.swanit.common.entity.convert.SysUserConvert;
import cn.swanit.common.entity.dataobject.SysUserDO;
import cn.swanit.common.entity.dto.SysUserDTO;
import cn.swanit.service.demo.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author chj
 * @date 2021年07月22日 11:21
 */

@Slf4j
@RestController
@RefreshScope
@RequestMapping("/user")
public class SysUserController {

    @Resource
    SysUserService sysUserService;

    @Resource
    SysUserConvert sysUserConvert;

    @GetMapping("/{userId}")
    public SysUserDTO info(@PathVariable(value = "userId") String userId) {
        SysUserDO sysUserDO = sysUserService.getById(userId);
        return sysUserConvert.convertDOToDTO(sysUserDO);
    }

    @GetMapping("/login")
    public SysUserDTO login(@RequestParam(value = "userAccount") String userAccount) {
        QueryWrapper<SysUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        SysUserDO sysUserDO = sysUserService.getOne(queryWrapper);
        return sysUserConvert.convertDOToDTO(sysUserDO);
    }

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public String user(@RequestBody SysUserDTO sysUserDTO) {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        String userId = String.valueOf(snowflake.nextId());
        SysUserDO sysUserDO = sysUserConvert.convertDTOToDO(sysUserDTO);
        sysUserDO.setUserId(userId);
        sysUserService.save(sysUserDO);
        return userId;
    }
}
